import React, {Component} from "react";
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import {saveUserInfoAction} from '@/store/action'
import Header from '@/components/header/header'
import AlertTip from '@/components/alertTip/alertTip'
import {getImgPath, setStorage} from '@/utils/common'
import PropType from 'prop-types'
import './login.scss'
import Api from '@/api/api'

class Login extends Component {
  static propTypes = {
    userInfo: PropType.object.isRequired,
    saveUserInfo: PropType.func.isRequired
  }

  state = {
    mobileCode: '',
    userAccount: '',
    hasAlert: false,
    alertText: '',
    password: '',
    codeNumber: '',
    captchaCodeImg: '',
    showPwd: true,
    loginWay: false
  }
  // 获取文本框输入的内容
  handleInput = (type, event) => {
    let value = event.target.value;
    let newState = {};

    newState[type] = value;
    this.setState(newState)
  }
  // 密码可见
  changePasswordType = () => {
    this.setState({
      showPwd: !this.state.showPwd
    })
  }
  // 获取验证码
  getCaptchaCode = async () => {
    // let res = await Api.getCaptchaCode()
    this.setState({
      // captchaCodeImg: res.code
    })
  }
  closeTip = () => {
    this.setState({
      hasAlert: false
    })
  }
  goBack = () => {
    this.props.history.goBack()
  }
  logout = (wait) => {
    if (!wait) {
      this.props.history.push('/login')
    }
    return this.state.logout
  }
  mobileLogin = async () => {
    let isValidate, alertText
    if (this.state.loginWay) {
    } else {
      if (!this.state.userAccount) {
        alertText = '请输入手机号/邮箱/用户名'
        isValidate = true
      } else if (!this.state.password) {
        alertText = '请输入密码'
        isValidate = true
      } else if (!this.state.codeNumber) {
        alertText = '请输入验证码'
        isValidate = true
      }
      if (isValidate) {
        this.setState({
          hasAlert: true,
          alertText
        })
        return
      }
    }
    let data = {
      username: this.state.userAccount,
      password: this.state.password,
      captcha_code: this.state.codeNumber
    }
    let userInfo = await Api.accountLogin(data)
    if (userInfo.tip) {
      this.setState({
        hasAlert: true,
        alertText: userInfo.response.message
      })
      if (!this.state.loginWay) this.getCaptchaCode().then();
      return
    }
    setStorage('userId', userInfo.user_id); // 存本地
    // 处理头像
    userInfo.imgpath = userInfo.avatar.indexOf('/') !== -1 ? '/img/' + userInfo.avatar : getImgPath()
    // 存store
    this.props.saveUserInfo(userInfo)
    this.props.history.push('/profile')
  }

  componentDidMount() {
    this.getCaptchaCode().then()
  }

  render() {
    return (
      <div className="login-container">
        <Header title="登录" goBack={this.goBack}/>
        {
          this.state.loginWay ?
            // 手机验证码登录
            <form className="login-form">
              <div className="input-container phone-number">
                <input type="text" placeholder="输入验证码" name="phone" maxLength="11" value={this.state.mobileCode}/>
                <button>获取验证码</button>
              </div>
            </form>
            :
            // 账号密码登录
            <form className="login-form">
              <div className="input-container">
                <input type="text" placeholder="账号" value={this.state.userAccount}
                       onChange={
                         this.handleInput.bind(this, 'userAccount')
                       }/>
              </div>
              <div className="input-container">
                <input type={this.state.showPwd ? 'text' : 'password'} placeholder='密码'
                       value={this.state.password}
                       onChange={this.handleInput.bind(this, 'password')
                       }/>
                <div className={`button-switch ${this.state.showPwd ? 'change-to-text' : ''}`}>
                  <div className={`circle-button ${this.state.showPwd ? 'trans_to_right' : ''}`}
                       onClick={
                         this.changePasswordType.bind(this)
                       }/>
                  <span>abc</span>
                  <span>...</span>
                </div>
              </div>
              <div className='input-container captcha-code-container'>
                <input type="text" placeholder='验证码' maxLength='4' value={this.state.codeNumber}
                       onChange={
                         this.handleInput.bind(this, 'codeNumber')
                       }/>
                <div className='img-change-img'>
                  <img src={this.state.captchaCodeImg} alt="img is wrong"/>
                  <div className='change-img' onClick={() => {
                    this.getCaptchaCode()
                  }}>
                    <p>看不清</p>
                    <p>换一张</p>
                  </div>
                </div>
              </div>
            </form>
        }

        <p className='login-tips'>
          温馨提示: 未注册过的账号, 登录时自动注册
        </p>
        <p className='login-tips'>
          注册过的用户可凭证账号密码登录
        </p>
        <div className='login-button' onClick={this.mobileLogin}>登录</div>
        <Link to='/forget' className='to-forget'>重置密码?</Link>

        {
          this.state.hasAlert &&
          <AlertTip
            alertText={this.state.alertText}
            logout={() => {
              return false
            }}
            closeTip={this.closeTip}
          />
        }

      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    userInfo: state.userInfo
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    saveUserInfo: (userInfo) => dispatch(saveUserInfoAction(userInfo))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)